import axios from "axios";
import {getTokenName, massageTip, messageConfirm, removeToken} from "../utils/util.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 定义后端接口地址前缀
axios.defaults.baseURL="http://localhost:8080"

export function doPost(url,data){
    return axios({
        method:'post',
        url: url,
        data: data,
        dataType: 'json'
    })
}

export function doPut(url,data){
    return axios({
        method:'put',
        url: url,
        data: data,
        dataType: 'json'
    })
}

export function doGet(url,params){
    return axios({
        method: 'get',
        url: url,
        params: params,
        dataType: 'json'
    })
}

export function doDelete(url,params){
    return axios({
        method: 'delete',
        url: url,
        params: params,
        dataType: 'json'
    })
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 获取Token
    let token = window.sessionStorage.getItem(getTokenName());
    if (!token){
        token=window.localStorage.getItem(getTokenName())
        if (token){
            config.headers['rememberMe']=true
        }
    }
    if (token){
        config.headers['Authorization'] = token;
    }
    return config;

}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    if(response.data.code>900){
        messageConfirm(response.data.msg+"，是否重新登录").then(() => {
            removeToken()
            // 确认登录，直接返回登录页
            window.location.href='/'
        }).catch(() => {
            massageTip('取消登录','warning')
        })
        return;
    }
    return response;
}, function (error) {

    // 对响应错误做点什么
    return Promise.reject(error);
});